package com.ss.springboot1.common.util;



import com.ss.springboot1.config.properties.DeviceProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * 设备核心业务类：单机箱场景，处理板卡、通道的关联逻辑
 */
@Component
@RequiredArgsConstructor
public class DeviceConfig {

    private final DeviceProperties deviceProperties;

     //1. 根据“板号”获取IP
    public String getIpByBoardId(int boardId) {
        String ip = deviceProperties.getBoardIps().get(boardId);
        if (ip == null) {
            throw new IllegalArgumentException("板号" + boardId + "未配置IP（检查application.yml）");
        }
        return ip;
    }

     // 2. 获取共用端口
    public int getCommonPort() {
        return deviceProperties.getCommonPort();
    }


     //3. 根据“通道号”计算板号（1-4→1号板，5-8→2号板...）

    public int getBoardIdByChannel(int channel) {
        DeviceProperties.ChannelConfig channelConfig = deviceProperties.getChannel();
        if (channel < channelConfig.getMin() || channel > channelConfig.getMax()) {
            throw new IllegalArgumentException("通道号必须为" + channelConfig.getMin() + "-" + channelConfig.getMax());
        }
        return (channel - 1) / channelConfig.getCountPerBoard() + 1;
    }

    //4. 计算通道在板卡内的“内部通道号”（如通道5→2号板的内部通道1）
    public int getBoardInnerChannel(int channel) {
        DeviceProperties.ChannelConfig channelConfig = deviceProperties.getChannel();
        return (channel - 1) % channelConfig.getCountPerBoard() + 1;
    }

    //5. 扩展：根据通道号直接获取板卡IP+端口（常用场景封装）

    public Map<String, Object> getBoardInfoByChannel(int channel) {
        int boardId = getBoardIdByChannel(channel);
        Map<String, Object> result = new HashMap<>();
        result.put("boardId", boardId);
        result.put("ip", getIpByBoardId(boardId));
        result.put("port", getCommonPort());
        result.put("innerChannel", getBoardInnerChannel(channel));
        return result;
    }
}